package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.util.Page;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.result.Result;
import com.dongdongshop.result.ResultEnum;
import com.dongdongshop.service.ElasticsearchService;
import com.dongdongshop.util.PageUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("es")
public class EsController {

    @Reference
    private ElasticsearchService elasticsearchService;

    @RequestMapping("toEsShow")
    public String toEsShow(String searchName, Model model){
        TbUser tbUser = (TbUser) SecurityUtils.getSubject().getPrincipal();
        if (null != tbUser){
            model.addAttribute("tbUser",tbUser.getUsername());
        }
        model.addAttribute("searchName",searchName);
        return "search";
    }

    @RequestMapping("getSearchByName")
    @ResponseBody
    public Result listSearchByName(@RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, String searchName) {
        try {
            PageUtil searchPage = elasticsearchService.listSearchByName(pageNum, pageSize, searchName);
            if (searchPage.getList() != null) {
                // System.out.println(searchPage.getTotalPage());
                return Result.jsonResponse(ResultEnum.OK).setData(searchPage);
            } else {
                return Result.jsonResponse(ResultEnum.FORBIDDEN);
            }
        } catch (Exception e) {
            return Result.jsonResponse(ResultEnum.INTERNAL_SERVER_ERROR);
        }
    }
}
